package controllers;

import form.EditPassword;
import form.Login;
import gateway.DatabaseGateway;
import form.Signup;
import gateway.exception.CarpoolDBException;
import play.data.Form;
import play.libs.Crypto;
import play.mvc.Controller;
import play.mvc.Result;
import session.CookieManager;
import views.html.*;
import views.html.user.login;
import views.html.user.register;

import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * UserActions: Tom
 * Date: 5-2-14
 * Time: 19:58
 */
public class UserActions extends Controller {



    /**
     * Loads the login form, if the session already contains a username redirect to the index.
     * @return
     */
    public static Result loginForm(){
        if (session().containsKey("username")){
            return redirect(routes.Application.index());
        }
        return ok(login.render("Login AtagCarpool", ""));
    }

    /*
     *  TODO what if /login is called and there is no session, but rememberme cookie is set?
     */

    /**
     * POST action for login. Loads data from a app.form.Login form.
     * Uses the DatabaseGateway to verify the login request.
     * @return
     */
    public static Result loginUser(){
        Login login = Form.form(Login.class).bindFromRequest().get();

        DatabaseGateway db = new DatabaseGateway();
        try {
            db.verifyUserLogin(login);
        } catch (CarpoolDBException e) {
            return ok(views.html.user.login.render("Login AtagCarpool", e.getMessage()));
        } catch (SQLException e) {
            return ok(views.html.user.login.render("Login AtagCarpool", "Something went wrong with the database."));
        }

        // login successful
        session().put("username", login.getEmail());
        if (login.isRemember()){
            CookieManager.setRememberMe(login.getEmail());
        }

        return redirect(routes.Application.index());
    }

    /**
     * Loads the registration form.
     * @return
     */
    public static Result registerForm(){
        return ok(register.render("Registration AtagCarpool", ""));
    }

    /**
     * POST action for registrating a user. Loads data from a app.form.Signup form.
     * Uses the DatabaseGateway to store a user.
     * @return
     */
    public static Result registerUser(){
        Signup signup = Form.form(Signup.class).bindFromRequest().get();

        DatabaseGateway db = new DatabaseGateway();
        try {
            db.insertUser(signup.toUser());
        } catch (CarpoolDBException e) {
            return ok(register.render("Registration AtagCarpool", e.getMessage()));
        }catch (SQLException e) {
            return ok(register.render("Registration AtagCarpool", "Something went wrong with the database."));
        }

        return ok(views.html.user.successful_registration.render("Login AtagCarpool", "Account '"+signup.getEmail()+"' has been created."));

    }


    public static Result editPasswordForm(){
        return ok(views.html.user.update_password.render(""));
    }

    public static Result editPassword(){
        EditPassword changes = Form.form(EditPassword.class).bindFromRequest().get();
        String email = session().get("username");
        if (email == null){
            return badRequest("Not logged in.");
        }

        DatabaseGateway db = new DatabaseGateway();
        try {
            db.editPassword(email, changes.getNew_password());
        } catch (CarpoolDBException e) {
            return ok(views.html.user.update_password.render("<p class='error'>" + e.getMessage() + "</p>"));
        } catch (SQLException e) {
            e.printStackTrace();
            return ok(views.html.user.update_password.render("<p class='error'>An error occurred, password not updated.</p>"));
        }

        return ok(views.html.user.update_password.render("Your password has been updated."));
    }





    /**
     * GET request to log out a user. Removes the rememberme cookie and destroys the user session.
     * @return
     */
    public static Result logout(){
        session().remove("username");
        response().discardCookie("rememberme");
        return redirect(routes.Application.index());
    }


    public static Result destroySession(){
        session().remove("username");
        return redirect(routes.Application.index());
    }

    public static Result destroyRememberme(){
        response().discardCookie("rememberme");
        return redirect(routes.Application.index());
    }

}
